import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/*
    事务提交
 */
public class JDBCDemo9 {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            //1.获取数据库连接
            connection = DBUtil.getConnection();
            //2.关闭自动提交，开启事务
            connection.setAutoCommit(false);  //关键步骤
            // 3.执行转账操作  A 账户扣款
            String sqlDebit = "UPDATE teacher SET salary=salary-? WHERE id=?";
            try (PreparedStatement debitstmt = connection.prepareStatement(sqlDebit)) {
                debitstmt.setInt(1, 500);
                debitstmt.setInt(2, 1);
                int rowsDebit = debitstmt.executeUpdate();
                if (rowsDebit != 1) {
                    throw new SQLException("扣款失败，账户不存在");
                }
            }
            //4.模拟网络异常
//            if (true) {
//                throw new SQLException("模拟网络中断");
//            }
            //5.执行转账操作 B 账户收款
            String sqlCredit = "UPDATE teacher SET salary=salary+? WHERE id=?";
            try (PreparedStatement creditStmt = connection.prepareStatement(sqlCredit)) {
                creditStmt.setInt(1, 500);
                creditStmt.setInt(2, 2);
                int rowsCredit = creditStmt.executeUpdate();
                if (rowsCredit != 1) {
                    throw new SQLException("收款失败，账户不存在");
                }

            }
            //6.提交事务
            connection.commit(); //所有操作成功，提交事务
            System.out.println("转账成功");
        } catch (SQLException e) {
            try {
                // 7.回滚事务（任何异常触发回滚）
                if (connection != null) {
                    connection.rollback();
                    System.out.println("事务回滚：" + e.getMessage());
                }
            } catch (SQLException rollbackEx) {
                System.err.println("回滚失败：" + rollbackEx.getMessage());
            }
        } finally {
            //8.恢复自动提交&关闭连接
            try {
                if (connection != null) {
                    connection.setAutoCommit(true);
                    connection.close();
                }
            } catch (SQLException closeEx) {
                System.err.println("关闭连接失败：" + closeEx.getMessage());
            }
        }
    }
}
